﻿using Furion;
using Furion.DatabaseAccessor;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Queer.AutoJob.Core.Entity;
using Queer.Util.Helper;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Queer.AutoJob
{
    public class JobCenter
    {
        public static void Start()
        {
            try
            {
                var serviceScopeFactory = App.GetService<IServiceScopeFactory>();
                var data = new List<AutoJobEntity>();
                using (var scope = serviceScopeFactory.CreateScope())
                {
                    var repository = scope.ServiceProvider.GetService<IRepository<AutoJobEntity>>();
                    data = repository.AsQueryable().ToList();
                }

                foreach (AutoJobEntity entity in data)
                {
                    if (entity.StartTime == null)
                        entity.StartTime = DateTime.Now;

                    DateTimeOffset starRunTime = DateBuilder.NextGivenSecondDate(entity.StartTime, 1);

                    if (entity.EndTime == null)
                        entity.EndTime = DateTime.MaxValue.AddDays(-1);

                    DateTimeOffset endRunTime = DateBuilder.NextGivenSecondDate(entity.EndTime, 1);

                    var scheduler = JobScheduler.GetScheduler();
                    IJobDetail job = JobBuilder.Create<JobExecute>().WithIdentity(entity.JobName, entity.JobGroupName).Build();
                    job.JobDataMap.Add("Id", entity.Id);

                    ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                                                 .StartAt(starRunTime)
                                                 .EndAt(endRunTime)
                                                 .WithIdentity(entity.JobName, entity.JobGroupName)
                                                 .WithCronSchedule(entity.CronExpression)
                                                 .Build();

                    scheduler.ScheduleJob(job, trigger);
                    scheduler.Start();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("查询自动任务列表失败！", ex);
            }
        }

        /// <summary>
        /// 添加任务计划
        /// </summary>
        public static void ClearScheduleJob()
        {
            try
            {
                JobScheduler.GetScheduler().Clear();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }
    }
}